package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class DataBaseActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView tv_database;
    private String mDatabaseName;

    @SuppressLint("Recycle")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_base);
        tv_database = findViewById(R.id.tv_database);
        findViewById(R.id.btn_database_create).setOnClickListener(this);
        findViewById(R.id.btn_database_delete).setOnClickListener(this);
        // 生成一个测试数据库的完整路径
        mDatabaseName = getFilesDir() + "/test.db";
        broadcast();
        ContentResolver resolver = getContentResolver();
        resolver.query(Uri.parse("content://com.example.myapplication.provider.MyDBProvider"),null,null,null,null);
    }

    /**
     * 动态发送广播
     */
    public void send(){
        Intent intent = new Intent();
        // action和filter的action保持一致
        intent.setAction("GUANGBO");
        sendBroadcast(intent);
    }

    /**
     * 静态发送广播
     */
    public void broadcast(){
        Intent intent = new Intent();
        intent.setAction("GUANGBO");
        intent.putExtra("name","123");
        intent.putExtra("pwd","123");
        /**
         * Android 8.0或者更高版本，发送广播的条件更加严苛，必须添加这一行内容
         * 第1个参数是指接收广播类的包名，第2个参数是指接收广播类的完整类名
         */
        intent.setComponent(new ComponentName(getPackageName(),getPackageName() + ".broadcast.MyBroadcastReceiver"));
        Log.i("d",getPackageName());
        sendBroadcast(intent);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        String desc = null;
        switch (v.getId()) {
            case R.id.btn_database_create:
                // 创建或打开数据库。数据库如果不存在就创建它，如果存在就打开它
                SQLiteDatabase db = openOrCreateDatabase(mDatabaseName, Context.MODE_PRIVATE, null);
                desc = String.format("数据库%s创建%s", db.getPath(), "成功");
                tv_database.setText(desc);
                break;

            case R.id.btn_database_delete:
                // 删除数据库
                boolean result = deleteDatabase(mDatabaseName);
                desc = String.format("数据库%s删除%s", mDatabaseName, result?"成功":"失败");
                tv_database.setText(desc);
                break;
        }
    }
}